package com.ingesup.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * @author FDEJEAN
 */

public class GenericDaoImpl <T> implements GenericDao <T>{
	
	protected static EntityManager em;
	private final Class<T> type;
	
	static {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("TpBddWebMailPu");
		em = emf.createEntityManager();
	}
	
	public GenericDaoImpl(Class<T> type) {
        this.type = type;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public T create (T toCreate) {
		em.getTransaction().begin();
		em.persist(toCreate);
		em.getTransaction().commit();
		return toCreate;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public T read (long id) {
		try {			
			return em.find(type, id);
		}
		catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void update(T toUpdate) {
		em.getTransaction().begin();
		em.merge(toUpdate);
		em.getTransaction().commit();
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void delete (T toDelete) {
		em.getTransaction().begin();
		em.remove(toDelete);
		em.getTransaction().commit();
	}
}
